package com.jf3q.common.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jf3q.common.constant.SysConstant;
import com.jf3q.common.domain.EduTeacher;
import com.jf3q.common.dto.EduTeacherRankDTO;
import com.jf3q.common.mapper.TeacherMapper;
import com.jf3q.common.service.TeacherService;
import com.jf3q.common.vo.TeacherDetailsVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 *
 */
@Service
public class TeacherServiceImpl extends ServiceImpl<TeacherMapper, EduTeacher> implements TeacherService {

    @Autowired
    StringRedisTemplate stringRedisTemplate;

    @Override
    @Scheduled(cron="0 0 2 * * ?")
    public List<EduTeacherRankDTO> saveTeacherRank() {
        List<EduTeacherRankDTO> rankDTOList = super.baseMapper.queryTeacherRank();
        rankDTOList.forEach(dto -> stringRedisTemplate.opsForZSet().add(SysConstant.REDIS_TEACHER_PLAY_COUNT_KEY,
                dto.getTeacherId(), dto.getPlayCount()));
        stringRedisTemplate.expire(SysConstant.REDIS_TEACHER_PLAY_COUNT_KEY, 24, TimeUnit.HOURS);
        return rankDTOList;
    }

    @Override
    public List<EduTeacher> queryTeacherRank() {
        Set<String> range = stringRedisTemplate.opsForZSet().reverseRange(SysConstant.REDIS_TEACHER_PLAY_COUNT_KEY, 0, -1);
        List<EduTeacher> teacherList =
                range.stream().map(id -> this.queryEduTeacherById(id)).collect(Collectors.toList());
        return teacherList;
    }

    @Override
    public EduTeacher queryEduTeacherById(String teacherId) {
        return baseMapper.selectById(teacherId);
    }

    @Override
    public void playTeacherVideo(String teacherId) {
        stringRedisTemplate.opsForZSet().incrementScore(SysConstant.REDIS_TEACHER_PLAY_COUNT_KEY, teacherId, 1);
    }
}




